//获取应用实例
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },

  
  judgeAuth:function(){
    var that = this
    wx.login({
      success: function(r){        
        var code = r.code
        if(code){
          wx.getUserInfo({
            success: function (res) {
              wx.request({
                url: 'http://' + app.globalData.ip +'/user/getUserInfo',
                data: {encryptedData: res.encryptedData, iv: res.iv, code: code},
                header: {                                                                                                                                                                                 
                  'content-type': 'application/x-www-form-urlencoded'
                },
                method: 'POST',
                success: function (data) {
                  //4.status=0解密失败，status=1解密成功后 获取自己服务器返回的结果
                  if (data.data.status == 1) {
                    //更新全局数据的用户信息和省份信息
                    app.globalData.userInfo = data.data.userInfo
                    app.globalData.hasUserInfo = true
                    wx.switchTab({
                      url: '../shouye/shouye',
                    })
                  } else {
                    wx.showModal({
                      content: "获取用户ID失败",
                    })
                  }
                },
                fail: function (res) {
                  wx.showModal({
                    content: "系统后台错误",
                  })
                }
              })

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (that.userInfoReadyCallback) {
                that.userInfoReadyCallback(res)
              }
            },
            fail: function () {
              wx.showModal({
                content: "获取用户信息失败",
              })
            }
          })
        }else{
          wx.showModal({
            content: "获取用户登录态失败",
          })
        }
        
      },
      fail:function(){
        callback(false)
      }
    })

    if (this.data.hasUserInfo == true) {
      wx.switchTab({
        url: '../shouye/shouye',
      })
    }
  },

  onLoad: function () {
    /*wx.getSetting({
      success:res=>{
        if (res.authSetting['scope.userInfo']){
          //已经授权了
          this.data.hasUserInfo = true
          this.judgeAuth();          
        }else{
          this.data.hasUserInfo = true
        }
      }
    })  */
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },
  //用来判断授权时点击的是 同意 还是 拒绝
  bindgetUserInfo: function (e) {    
    if (e.detail.rawData) {
      //用户点击的是允许
      this.judgeAuth()

    } else {
      this.setData({
        hasUserInfo: false
      })
    }
  },
  
})